﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class PropManager 
{
    
    /// <summary>
    /// 道具字典 [槽位,道具]
    /// </summary>
    public Dictionary<int,PropBase> props { get; } = new Dictionary<int, PropBase>();

    private PlayerData playerData;

    public PropManager(PlayerData playerData)
    {
        this.playerData = playerData;
        props.Add(1, null);
        props.Add(2, null);
        props.Add(3, null);
        props.Add(4, null);
        props.Add(5, null);
        EventManager.Listen(EventName.Player.DataChange, PlayerDataChange);
    }



    /// <summary>
    /// 获得道具
    /// </summary>
    /// <param name="prop">被获得的道具</param>
    /// <returns>剩余未获取的道具数量</returns>
    public int GetProp(PropBase prop)
    {
        var p = props.Values.Where(p_t => p_t!=null&&p_t.Name == prop.Name).FirstOrDefault();
        if (p==null)
        {
            foreach (var item in props)
            {
                if (item.Value == null)
                {
                    props.Add(item.Key, prop);
                    return 0;
                }
            }
        }
        else
        {
            foreach (var item in props)
            {
                if (item.Value!=null&&item.Value.Name==prop.Name)
                {
                    return props[item.Key].GetItemSecond(prop.Num);
                }
            }
            
        }
        return prop.Num;
    }

    public void ChangePropPos(int slot1,int slot2)
    {
        var temp = props[slot1];
        props[slot1] = props[slot2];
        props[slot2] = temp;
    }


    public void UseItem(int slot)
    {
        if (props[slot]!=null)
        {
            var isSuc = props[slot].UseItem();
            EventManager.Broadcast(EventName.Player.UserProp, playerData, isSuc, props[slot]);
        }
    }

    private void PlayerDataChange(object[] o)
    {
        //TODO 冷却时间设置
        int id = (int)o[0];
        if (id==playerData.ID)
        {
            foreach (var item in props.Values)
            {
                //item.SulCoolTime(playerData.time);
            }
        }
    }

    ~PropManager(){
        EventManager.UnListen(EventName.Player.DataChange, PlayerDataChange);
    }
}
